﻿using System;
using YJKGridTopologyCal.Index.Quadtree;

namespace YJKGridTopologyCal.Index.Bintree
{
	public class Key
	{
		public static int ComputeLevel(Interval interval)
		{
			return DoubleBits.GetExponent(interval.Width) + 1;
		}

		public Key(Interval interval)
		{
			this.ComputeKey(interval);
		}

		public double Point
		{
			get
			{
				return this._pt;
			}
		}

		public int Level
		{
			get
			{
				return this._level;
			}
		}

		public Interval Interval
		{
			get
			{
				return this._interval;
			}
		}

		public void ComputeKey(Interval itemInterval)
		{
			this._level = Key.ComputeLevel(itemInterval);
			this._interval = new Interval();
			this.ComputeInterval(this._level, itemInterval);
			while (!this._interval.Contains(itemInterval))
			{
				this._level++;
				this.ComputeInterval(this._level, itemInterval);
			}
		}

		private void ComputeInterval(int level, Interval itemInterval)
		{
			double num = DoubleBits.PowerOf2(level);
			this._pt = Math.Floor(itemInterval.Min / num) * num;
			this._interval.Init(this._pt, this._pt + num);
		}

		private double _pt;

		private int _level;

		private Interval _interval;
	}
}
